<template>
  <div class="school_infs">
    <Row type="flex" justify="center">
      <Col span="10">
        <Card :style="{ height: height}">
          <p slot="title">
            <Icon type="person"></Icon>
            用户列表
          </p>
          <Row type="flex" justify="space-between">
            <div class="db_inline">
              <Input v-model="user.page.fullName" placeholder="姓名关键字" class="proposalTitle"/>
              <Button type="info" @click="searchFn">
                <Icon
                  type="ios-search-strong"></Icon>
              </Button>
              <span @click="reflushUserFn">
			             <Button type="ghost"><Icon type="refresh"></Icon></Button>
			        </span>
            </div>
           <!-- <div class="control">
              <Button @click="addUserFn" type="info">
                <Icon type="person"></Icon>
                <Icon type="plus"></Icon>
              </Button>
            </div>-->
          </Row>
          <Row class="margin-top-10">
            <Table ref="userTable" stripe :columns="user.userColumns" :style="{ height: tableHeight}"
                   :data="user.userTable"></Table>
          </Row>
          <Row type="flex" justify="end" class="footer">
            <div class="margin-top-10">
              <Page :total="user.page.total" :current="user.page.current" simple :page-size="user.page.size"
                    @on-change="pageChange"
                    show-elevator></Page>
            </div>
          </Row>
        </Card>
      </Col>
      <Col span="9">
        <Card :style="{ height: height}" style="overflow-y: auto">
          <p slot="title">
            <Icon type="person-stalker"></Icon>
            角色列表
          </p>
          <Button slot="extra" type="info" @click="saveUserRoleFn">保 存</Button>
          <Row type="flex" justify="space-between">
            <div class="db_inline">
            </div>
          <div class="control">
              <Button @click="addRoleFn" type="info">
                <Icon type="person-stalker"></Icon>
                <Icon type="plus"></Icon>
              </Button>
            </div>
          </Row>
          <Row class="margin-top-10">
            <Table ref="roleTable" stripe :columns="role.columns" :style="{ height: tableHeight}"
                   :data="role.tableData" @on-selection-change="roleSelectChange"></Table>
          </Row>
          <Row type="flex" justify="end" class="footer">
            <div class="margin-top-10">
              <Page :total="role.page.total" :current="role.page.current" simple :page-size="role.page.size"
                    @on-change="rolePageChangeFn"
                    show-elevator></Page>
            </div>
          </Row>
        </Card>
      </Col>
      <Col span="5">
        <Card :style="{ height: height}">
          <p slot="title">
            <Icon type="android-menu"></Icon>
            菜单列表
          </p>
          <Button slot="extra" type="info" @click="savePermissionFn">保 存</Button>
          <Ztree :nodeData="menu.treeData" @scope-change="scopeChange" ref="menuZtree">

          </Ztree>
        </Card>
      </Col>
    </Row>
    <Modal v-model="user.visible" :title="user.title" v-on:on-ok="submitAddUserFn" :mask-closable="false"
           width="600" v-on:on-cancel="cancelAddUserFn">
      <Form ref="userForm" :model="user.form" :label-width="100" label-position="right" :rules="user.rules">
        <FormItem label="登录名" prop="username">
          <Input v-model="user.form.username" clearable style="width:90%"/>
        </FormItem>
        <FormItem label="姓名" prop="fullName">
          <Input v-model="user.form.fullName" clearable style="width:90%"/>
        </FormItem>
        <FormItem label="密码" prop="pwd" v-if="!user.isEdit">
          <Input v-model="user.form.pwd" clearable type="password"
                 style="width:60%"/>&nbsp;&nbsp;<span>(默认密码为123456)</span>
        </FormItem>
        <FormItem label="再次输入" prop="rePwd" v-if="!user.isEdit">
          <Input style="width:60%" type="password" clearable v-model="user.form.rePwd"
                 :disabled="user.isEdit"/>&nbsp;&nbsp;<span>(请确保两次输入密码一致)</span>
        </FormItem>
        <FormItem label="状态" prop="isLocked">
          <RadioGroup v-model="user.isLocked">
            <Radio label="0">启用</Radio>
            <Radio label="1">停用</Radio>
          </RadioGroup>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancelAddUserFn">取消</Button>
        <Button type="primary" @click="submitAddUserFn" :loading="false">确定</Button>
      </div>
    </Modal>
    <Modal v-model="role.visible" :title="role.title" v-on:on-ok="submitAddRoleFn" :mask-closable="false" width="540"
           v-on:on-cancel="cancelAddRoleFn">
      <Form ref="roleForm" :model="role.form" :label-width="100" label-position="right" :rules="role.rules">
        <FormItem label="角色名" prop="roleName">
          <Input v-model="role.form.roleName" style="width:63%"/>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancelAddRoleFn">取消</Button>
        <Button type="primary" @click="submitAddRoleFn" :loading="false">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import API from "@/api/api";
  import VmBtable from "@/components/vm/vm-btable";
  import Ztree from '@/components/ztree/Ztree';

  export default {
    name: "Permission",
    components: {
      VmBtable,
      Ztree
    },
    data() {
      const pwdValidator = (rule, value, callback) => {
        if (value !== this.user.form.pwd) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      };
      return {
        height: '',
        tableHeight: '',
        user: {
          page: {
            current: 1,
            size: 15,
            total: 0,
            fullName: '',
          },
          selectedId: '',
          userColumns: [
            {
              title: '选择',
              align: 'center',
              minWidth: 80,
              render: (h, params) => {
                let id = params.row.id;
                let selected = this.user.selectedId === id;
                let _this = this;
                return h('div', [h('Radio', {
                  props: {
                    value: selected
                  },
                  on: {
                    input: () => {
                      _this.user.selectedId = id;
                      _this.getRole();
                    }
                  }
                })])
              }
            },
            {
              title: '登录名',
              key: 'username',
              align: 'center',
              minWidth:120
            },
            {
              title: '姓名',
              key: 'fullName',
              align: 'center',
              minWidth: 120
            },
            {
              title: '状态',
              key: 'isLocked',
              align: 'center',
              minWidth: 100,
              render: (h, params) => {
                return h('div', params.row.isLocked === "0" ? "启用" : "停用");
              }
            }
            , {
              title: '操作',
              type: "operation",
              width: 100,
              render: (h, param) => {
                let status = param.row.isLocked;
                let btn = [];
                let edit = h('Icon', {
                  props: {
                    type: 'edit',
                    size: '15'
                  },
                  style: {
                    color: 'blur',
                    cursor: 'pointer',
                    marginRight: '10px'
                  },
                  on: {
                    click: () => {
                      this.editUser(param.row);
                    }
                  }
                });
                let lockBtn = h('Icon', {
                  props: {
                    type: 'locked',
                    size: '15'
                  },
                  style: {
                    color: 'orange',
                    cursor: 'pointer',
                    marginRight: '10px'
                  },
                  on: {
                    click: () => {
                      this.lockUser(param.row);
                    }
                  }
                });
                let unLockBtn = h('Icon', {
                  props: {
                    type: 'unlocked',
                    size: '15'
                  },
                  style: {
                    color: 'green',
                    cursor: 'pointer',
                    marginRight: '10px'
                  },
                  on: {
                    click: () => {
                      this.unLockUser(param.row);
                    }
                  }
                });
                let delBtn = h('Icon', {
                  props: {
                    type: 'trash-a',
                    size: '16'
                  },
                  style: {
                    color: 'red',
                    cursor: 'pointer',
                    marginLeft: '5px'
                  },
                  on: {
                    click: () => {
                      this.deleteUser(param.row);
                    }
                  }
                });
                if (status === '1') {
                  btn.push(unLockBtn);
                } else {
                  btn.push(lockBtn);
                }
                btn.push(edit);
                btn.push(delBtn);
                return btn;
              }
            }
          ],
          userTable: [],
          Height: 40,
          isEdit: false,
          save_loading: false,
          title: "",
          visible: false,
          submiting: false,
          isLocked: '1',
          form: {
            id: '',
            username: "",
            fullName: "",
            pwdExpireDate: "",
            isLocked: "0",
            pwd: '',
            rePwd: ''
          },
          rules: {
            'username': [{
              required: true,
              trigger: 'blur',
              message: '请输入用户名'
            }],
            'fullName': [{
              required: true,
              trigger: 'blur',
              message: '请输入名字'
            }],
            pwd: [{
              type: 'string',
              min: 6,
              max: 16,
              message: '密码长度为6-16个字符串',
              trigger: 'blur'
            }],
            'rePwd': [{
              validator: pwdValidator,
              trigger: 'blur'
            }]
          },
        },
        role: {
          isEdit: false,
          save_loading: false,
          title: "",
          visible: false,
          submiting: false,
          page: {
            current: 1,
            size: 15,
            total: 0,
            userId: '',
          },
          selectedId: '',
          columns: [
            {
              type: 'selection',
              align: 'center',
              minWidth: 80,
            },
            {
              title: '角色名',
              key: 'roleName',
              align: 'center',
              minWidth:120
            },
            {
              title: '创建时间',
              key: 'createTime',
              align: 'center',
              sortable: true,
              sortType: 'asc',
              minWidth:160
            },
            {
              title: '操作',
              type: "operation",
              minWidth: 100,
              render: (h, param) => {
                let btn = [];
                let edit = h('Icon', {
                  props: {
                    type: 'edit',
                    size: '15'
                  },
                  style: {
                    color: 'blur',
                    cursor: 'pointer',
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.editRoleFn(param.row);
                    }
                  }
                });
                let delBtn = h('Icon', {
                  props: {
                    type: 'trash-a',
                    size: '16'
                  },
                  style: {
                    color: 'red',
                    cursor: 'pointer',
                    marginLeft: '5px'
                  },
                  on: {
                    click: () => {
                      this.deleteRoleFn(param.row);
                    }
                  }
                });
                btn.push(edit);
                btn.push(delBtn);
                return btn;
              }
            }
          ],
          tableData: [],
          form: {
            id: '',
            roleName: '',
          },
          rules: {
            'roleName': [{
              required: true,
              trigger: 'blur',
              message: '请输入角色名'
            }],
          },
          operate: []
        },
        menu: {
          searchParams: {
            roleIds: '',
            scope: 'p'
          },
          treeData: []
        },
      }
    },
    methods: {
      scopeChange(scope) {
        this.menu.searchParams.scope = scope;
        this.queryMenu();
      },
      getChecked() {
        // console.log(this.$refs.menuZtree.getChecked())
      },
      getRole() {
        this.role.page.userId = this.user.selectedId;
        this.queryRole();
      },
      searchFn() {
        this.queryFn();
      },
      reflushUserFn() {
        this.user.page.fullName = '';
        this.user.page.current = 1;
        this.menu.searchParams.scope = 'p'
        this.$refs.menuZtree.initScope();
        this.queryFn();
      },
      addUserFn() {
        Object.assign(this.user, {
          title: "添加用户",
          visible: true,
          isEdit: false,
          form: {id: ''}
        });
      },
      lockUser(user) {
        this.$Modal.confirm({
          title: '警告',
          content: '是否锁定用户：' + user.fullName + '的账号?',
          onOk: () => {
            let obj = {
              id: user.id
            };
            API.lockUser(obj).then(resp => {
              this.queryFn();
              ;
            })
          }
        });
      },
      unLockUser(user) {
        this.$Modal.confirm({
          title: '警告',
          content: '确认解锁用户：' + user.fullName + '的账号?',
          onOk: () => {
            let obj = {
              id: user.id
            };
            API.unLockUser(obj).then(resp => {
              this.queryFn();
              ;
            })
          }
        });
      },
      editUser(user) {
        Object.assign(this.user, {
          title: "编辑",
          visible: true,
          isEdit: true
        });
        this.user.isLocked = user.isLocked;
        Object.assign(this.user.form, user);
      },
      deleteUser(user) {
        this.$Modal.confirm({
          title: '警告',
          content: '是否删除该用户？',
          onOk: () => {
            API.delUser({id: user.id}).then(resp => {
              this.queryFn();
            })
          }
        });
      },
      queryFn() {
        API.fetchUsers(this.user.page).then(
          res => {
            let data = res.data;
            this.user.selectedId = data.records[0].id;
            this.user.userTable = data.records;
            this.user.page.total = data.total;
            this.role.page.userId = data.records[0].id;
            this.queryRole();
          },
          error => {
            this.$Message.info(error.msg);
          }
        );
      },
      pageChange(val) {
        this.page.current = val;
        this.queryFn();
      },
      userCompleteFn() {
        this.user.visible = false;
        this.$refs.userForm.resetFields();
      },
      cancelAddUserFn() {
        this.user.visible = false;
      },
      submitAddUserFn() {
        this.$refs.userForm.validate(valid => {
          if (valid) {
            this.user.form.isLocked = this.user.isLocked;
            if (this.user.form.id) {
              API.updateUser(this.user.form).then(
                res => {
                  this.userCompleteFn();
                  this.queryFn();
                },
                error => {
                  this.$Message.info(error.msg);
                }
              );
            } else {
              API.createUser(this.user.form).then(resp => {
                this.userCompleteFn();
                this.queryFn();
              })
            }
          } else {
            return false;
          }
        });
      },
      rolePageChangeFn(current) {
        this.role.page.current = current;
      },
      addRoleFn() {
        Object.assign(this.role, {
          title: "新增角色",
          visible: true,
          form: {id: ''},
          isEdit: false
        });
      },
      editRoleFn(role) {
        Object.assign(this.role, {
          title: "编辑角色",
          visible: true,
          isEdit: true
        });
        Object.assign(this.role.form, role);
      },
      deleteRoleFn(role) {
        this.$Modal.confirm({
          title: '警告',
          content: '是否删除该角色？',
          onOk: () => {
            API.delRole({id: role.id}).then(resp => {
              this.queryRole();
            })
          }
        });
      },
      completeRoleFn() {
        this.role.visible = false;
        this.$refs.roleForm.resetFields();
      },
      roleSelectChange(selection) {
        let roleIds = [];
        selection.map(role => {
          roleIds.push(role.id)
        });
        this.menu.searchParams.roleIds = roleIds.join();
        this.queryMenu();
      },
      cancelAddRoleFn() {
        this.role.visible = false;
      },
      submitAddRoleFn() {
        this.$refs.roleForm.validate(valid => {
          if (valid) {
            let data = Object.assign({}, this.role.form);
            if (data && data.id) {
              API.updateRole(data).then(
                res => {
                  this.completeRoleFn();
                  this.queryFn();
                }
              );
            } else {
              API.createRole(data).then(
                res => {
                  this.completeRoleFn();
                  this.queryFn();
                }
              );
            }
          } else {
            return false;
          }
        });
      },
      queryRole() {
        API.fetchRole(this.role.page).then(
          res => {
            let data = res.data.records;
            let roleIds = [];
            for (let i in data) {
              if (data[i].checked) {
                data[i]._checked = true;
                roleIds.push(data[i].id);
              }
            }
            this.menu.searchParams.roleIds = roleIds.join();
            this.role.tableData = data;
            this.role.page.total = res.data.total;
            this.queryMenu();
          }
        );
      },
      queryMenu() {
        API.fetchMenu(this.menu.searchParams).then(resp => {
          this.menu.treeData = resp.data;
        })
      },
      saveUserRoleFn() {
        let roleIds = this.menu.searchParams.roleIds.split(",");
        let msg = roleIds.length === 0 ? '是否清除当前选择用户的角色？' : '是否保存当前用户所选角色？';
        this.$Modal.confirm({
          title: '提示',
          content: msg,
          onOk: () => {
            let obj = {
              userId: this.user.selectedId,
              roleIds: roleIds
            };
            API.insertUserRole(obj).then(resp => {
              this.queryFn();
            })
          }
        })
      },
      savePermissionFn() {
        let roleIds = this.menu.searchParams.roleIds.split(",");
        if (roleIds.length === 0) {
          this.$Message.warning('请选择角色！');
          return;
        }
        let menus = this.$refs.menuZtree.getChecked();
        let msg = menus.length === 0 ? '是否清空所选角色的权限？' : '是否保存当前角色所选菜单?';
        let menuIds = [];
        for (let i in menus) {
          menuIds.push(menus[i].id);
        }
        this.$Modal.confirm({
          title: '提示',
          content: msg,
          onOk: () => {
            let obj = {
              roleIds: roleIds,
              menuIds: menuIds,
              scope: this.menu.searchParams.scope
            };
            API.updateRoleResource(obj).then(resp => {
              this.queryRole();
            })
          }
        })
      },
      setHeight() {
        let mHeight = $(window).outerHeight();
        let hHeight = $('.ivu-card-head').outerHeight();
        let fHeight = $('#footer').outerHeight();
        let height = mHeight - hHeight - fHeight - 15;
        this.height = height + 'px';
        this.tableHeight = height - 180 + 'px';
      }
    },
    mounted() {
      this.setHeight();
      this.queryFn();
    }
  }
</script>

<style scoped>
  .proposalTitle {
    width: 120px;
    margin-right: 4px;
  }
</style>
